<template>
  <a-spin :spinning="confirmLoading">

        <a-tabs :activeKey="customActiveKey" :tabBarStyle="{ textAlign: 'left', borderBottom: 'unset' }"  @change="handleTabClick">
          <a-tab-pane key="tab1" tab="Basic">
            <j-form-container :disabled="formDisabled">
              <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">

                <a-row>
                  <a-col :span="12">
                    <a-form-model-item label="Course Type"  :wrapperCol="wrapperCol" prop="courseType">
                      <j-dict-select-tag type="list" v-model="model.courseType"
                                         :disabled="stimeDisabled"
                                         dictCode="courseType"
                                         :triggerChange="true"
                                         @change="courseTypeChange"
                                         placeholder="" />
                    </a-form-model-item>
                  </a-col>

                  <a-col :span="12">
                    <a-form-model-item label="Teacher"  :wrapperCol="wrapperCol" prop="tearcherName">
                      <JSelectTeacher  :buttons="false" @select="teacherInput" v-model="model.tearcherName" />
                    </a-form-model-item>
                  </a-col>
                </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item label="Category" :wrapperCol="wrapperCol" prop="categoryCode">
                    <j-tree-dict v-model="model.categoryCode" field= "code" @change="categoryChange"   parentCode="B03" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="6">
                  <a-form-model-item label="ClassType"  :wrapperCol="wrapperCol" prop="classType">
                    <j-dict-select-tag type="list" v-model="model.classType" dictCode="classType" placeholder="" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="6">
                  <a-form-model-item label="Class Site"   :wrapperCol="wrapperCol" prop="classSite">
                    <j-dict-select-tag type="list" v-model="model.classSite" dictCode="location" placeholder="" />
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item label="Course Name"   :wrapperCol="wrapperCol" prop="name">
                    <a-input v-model="model.name" placeholder=""  ></a-input>
                  </a-form-model-item>
                </a-col>

                <a-col :span="12">
                  <a-form-model-item label="Grade"  :wrapperCol="wrapperCol" prop="grade">
                    <j-dict-select-tag type="list" v-model="model.grade" dictCode="grade" placeholder="" />
                  </a-form-model-item>
                </a-col>

              </a-row>

              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="Term" v-if="courseType"  :wrapperCol="wrapperCol1" prop="term">
                    <j-dict-select-tag type="list" v-model="model.term" dictCode="term" placeholder="" style="width: 100%"/>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="12">
                  <a-form-model-item label="Course Hours" :wrapperCol="wrapperCol" prop="hours">
                    <a-input-number v-model="model.hours"  :disabled="stimeDisabled" placeholder="" style="width: 100%" />
                  </a-form-model-item>
                </a-col>

                <a-col :span="12">
                  <a-form-model-item label="Total Course Price" :wrapperCol="wrapperCol" prop="price">
                    <a-input-number
                       v-model="model.price"
                       style="width: 100%"
                        :formatter="value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                        :parser="value => value.replace(/\$\s?|(,*)/g, '')">
                    </a-input-number>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="12">
                  <a-form-model-item label="Start Date"  :wrapperCol="wrapperCol" prop="startTime">
                    <a-range-picker @change="onDateChange"  :format="dateFormat"  v-model="defTimeArray"   :disabled="stimeDisabled" style="width: 100%" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item label="Maximum Students" v-if="courseType" :wrapperCol="wrapperCol" prop="maxStudent">
                    <a-input-number v-model="model.maxStudent"  placeholder="" style="width: 100%" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item label="Sub type" v-if="!courseType" :wrapperCol="wrapperCol" prop="courseSubType">
                    <j-dict-select-tag type="list" v-model="model.courseSubType" dictCode="courseSubType" placeholder="" style="width: 100%"/>
                  </a-form-model-item>
                </a-col>
              </a-row>
                <a-row>
                  <a-col :span="24">
                    <a-form-model-item  :wrapperCol="wrapperCol1" label="Memo">
                      <a-textarea v-model="model.memo" @change="handMemoChange" :maxLength="250" allow-clear />

                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-form-model>
            </j-form-container>
          </a-tab-pane>
          <a-tab-pane key="tab2" tab="Student" v-if="isShowTab2">
              <CourseStudentInfoList :courseId="this.model.id" :disabled="formDisabled"/>
          </a-tab-pane>
        </a-tabs>
  </a-spin>

</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import JSelectTeacher from '../../person/teacher/JSelectTeacher'
  import { validateDuplicateValue } from '@/utils/util'
  import CourseStudentInfoList from "../CourseStudentInfoList";
  import Vue from 'vue'
  import moment from 'moment';


  export default {
    name: 'CourseInfoForm',
    components: {
      JSelectTeacher,
      CourseStudentInfoList,
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      let aData = new Date();
      let ntime = aData.getFullYear() + "-" + (aData.getMonth() + 1) + "-" + aData.getDate();
      let sDisabled = false;
      return {
        isShowTab2:true,
        defTimeArray:[],
        dateFormat: 'YYYY-MM-DD',
        customActiveKey:'tab1',
        ntime:ntime,
        courseType:true,
        stimeDisabled:sDisabled,
        editDisabled:false,
        priceFormat:'1,000',
        model:{
          id:0,
          courseType:2,
          maxStudent:10,
          hours:10,
          price:1000,
          currency:'$'
         },
        form : {
          layout: 'vertical',
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 23 },
        },
        wrapperCol1: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
          categoryCode: [
            { required: true, message: 'Please select Category Code!'},
          ],
          classType: [
            { required: true, message: 'Please select ClassType!'},
          ],
          courseSubType: [
            { required: true, message: 'Please select Sub Type!'},
          ],
          name: [
            { required: true, message: 'Please enter name!'},
          ],
          courseType: [
            { required: true, message: 'Please select type!'},
          ],
          grade: [
            { required: true, message: 'Please select grade!'},
          ],
          tearcherName: [
            { required: true, message: 'Please select Teacher!'},
          ],
          term: [
            { required: false, message: 'Please select Term!'},
          ],
          hours: [
            { required: true, message: 'Please enter course hours!'},
          ],
          priceFormat: [
            { required: true, message: 'Please enter total course price!'},
          ],
          startTime: [
            { required: true, message: 'Please select start date!'},
          ],
          endTime: [
            { required: true, message: 'Please select end date!'},
          ],
          maxStudent: [
            { required: true, message: 'Please enter Maximum Students!'},
          ],
        },
        url: {
          add: "/sistersophie/courseInfo/add",
          edit: "/sistersophie/courseInfo/edit",
          queryById: "/sistersophie/courseInfo/queryById"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {

       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      moment,
      handMemoChange(e){
        let val = this.model.memo;
        if(!val) return '';
        val = val.toString()
        let srcValArray = val.split(' ') //按照空格分割;
        this.model.memo = this.commonChangeValToUpper(srcValArray);
      },
      formatNumber(value) {
        value += '';
        const list = value.split('.');
        const prefix = list[0].charAt(0) === '-' ? '-' : '';
        let num = prefix ? list[0].slice(1) : list[0];
        let result = '';
        while (num.length > 3) {
          result = `,${num.slice(-3)}${result}`;
          num = num.slice(0, num.length - 3);
        }
        if (num) {
          result = num + result;
        }
        return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
      },
      onPriceChange(e) {
        let { value } = e.target;
        if(value == ''){
          this.priceFormat = '';
          return;
        }else {
          value = value.replaceAll(',', '');
        }
        console.info('value -->' + value);
        const reg = /^-?[0-9]*(\.[0-9]*)?$/;
        if ((!isNaN(value) && reg.test(value)) || value === '-')
        {
          this.model.price = parseFloat(value);
          console.info('format -->' + this.formatNumber(this.model.price));
          this.priceFormat=this.formatNumber(this.model.price);
          console.info(this.priceFormat);
        }else{
          return false;
        }

      },
      onPriceBlur() {
        const {onPriceChange} = this;
        let value = this.priceFormat;
        console.info('onPriceBlur --> ' + value);
       /* if(!value){
          value = value.replace(',', '');
        }*/
        let valueTemp = value;
        console.info('onPriceBlur --> ' + value);
        if (value.charAt(value.length - 1) === '.' || value === '-') {
          onPriceChange({ value: value.slice(0, -1) });
        }
      },
      onDateChange(date, dateString) {
        if(dateString != null && dateString.length > 1){
         /* this.model.startTime = dateString[0];
          this.model.endTime = dateString[1];*/
          Vue.set(this.model, "startTime", dateString[0]);
          Vue.set(this.model, "endTime", dateString[1]);
          // this.defTimeArray = date;
        }
      },
      handleTabClick(key){
        this.customActiveKey = key
      },
      courseTypeChange(val){
        if(val === '1'){
          this.courseType = false;
          Vue.set(this.model, "endTime", null);
          Vue.set(this.model, "maxStudent", null);
          Vue.set(this.model, "term", null);
        }else if(val === '2'){
          this.courseType = true;
          Vue.set(this.model, "maxStudent", 10);
          Vue.set(this.model, "endTime", this.ntime);
        }
        Vue.set(this.model, "courseType", val);
      },
      categoryChange(val,label){
        this.model.categoryName = label;
      },
      teacherInput(rows){
        if(rows.length > 0 ){
          this.model.teacherId = rows[0].id;
          this.model.teacherFirstName = rows[0].firstName;
          this.model.teacherLastName = rows[0].lastName;
        }else{
          this.model.teacherId = "";
          this.model.teacherFirstName = "";
          this.model.teacherLastName = "";
        }
      },
      add () {
        this.isShowTab2 = false;
        this.edit(this.modelDefault,1);
      },
      edit (record,type) {
        if(type != 1){
          this.isShowTab2 = true;
        }
        this.model = Object.assign({}, record);
        if(this.model.startTime && this.model.endTime){
          let sdate = new Date(this.model.startTime);
          if(new Date().getTime() >= sdate.getTime()){
            this.stimeDisabled = true;
          }
          let smont = moment(this.model.startTime, this.dateFormat);
          let emont = moment(this.model.endTime, this.dateFormat);
          this.defTimeArray = [];
          this.defTimeArray.push(smont);
          this.defTimeArray.push(emont);
        }
        if(this.model.courseType === 1){
         this.courseType = false;
        }
        this.visible = true;
       },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
      commonChangeValToUpper(srcValArray){
        let temp = '';
        for(let i=0;i<srcValArray.length;i++){
          if(i == 0){
            temp = temp + this.upperVal(srcValArray[i])
          }else {
            temp = temp + ' ' + this.upperVal(srcValArray[i]);
          }
        }
        return temp;
      },
      upperVal (value) {
        if (!value) return ''
        value = value.toString()
        return value.charAt(0).toUpperCase() + value.slice(1)
      },
    }
  }
</script>